package com.iter.devbox.datastructure;

/**
 * 链式栈
 * 
 * @author Jimly
 */
public class Linkstack {

	/**栈内的每个数据结点*/
	private Node node;
	
	/**栈内的数据结点个数*/
	private int nodeCount;
	
	public Linkstack() {
	}
	
	/**清空栈*/
	public boolean clear() {
		node = null;
		nodeCount = 0;
		return true;
	}
	
	/**栈是否为空*/
	public boolean isEmpty() {
		if (null==node || nodeCount==0) {
			return true;
		}
		return false;
	}
	
	/**获取栈顶元素*/
	public Object peek() {
		if (null==node || nodeCount==0) {
			throw new RuntimeException("栈为空");
		}
		Node top = this.node;
		for (int i=0; i<nodeCount-1; i++) {
			top = top.next;
		}
		return top.item;
	}
	
	/**向栈顶压入元素*/
	public Object push(Object object) {
		Node newNode = new Node(object, null);
		if (node == null) {
			node = newNode;
		} else {
			Node top = this.node;
			for (int i=0; i<nodeCount-1; i++) {
				top = top.next;
			}
			top.next = newNode;
		}
		nodeCount ++;
		return object;
	}
	
	/**从栈顶弹出元素*/
	public Object pop() {
		if (null==node || nodeCount==0) {
			throw new RuntimeException("栈为空");
		}
		Node top = this.node;
		for (int i=0; i<nodeCount-1; i++) {
			top = top.next;
		}
		nodeCount --;
		return top.item;
	}
	
	/**当前栈内元素个数*/
	public int size () {
		return nodeCount;
	}
	
	private static class Node {
		/**前一个元素*/
		private Node next;
		/**数据*/
		private Object item;
		
		public Node(Object item, Node next) {
            this.item = item;
            this.next = next;
        }
	}
	
	public static void main(String[] args) {
		Linkstack linkstack = new Linkstack();
		linkstack.push("1");
		linkstack.push("2");
		linkstack.push("3");
		linkstack.push("4");
		linkstack.push("5");
		System.out.println("栈元素个数：" + linkstack.size());
		System.out.println("获取栈顶元素：" + linkstack.peek());
		System.out.println("弹出栈顶元素：" + linkstack.pop());
		System.out.println("出栈一个后元素个数：" + linkstack.size());
		System.out.println("栈是否为空：" + linkstack.isEmpty());
		System.out.println("获取栈顶元素：" + linkstack.peek());
		System.out.println("栈清空：" + linkstack.clear());
	}
}
